package auth

import (
	"GoScaffoldDemo/config"
	jwtutil "GoScaffoldDemo/utils/Jwtutil"
	"GoScaffoldDemo/utils/logsutil"

	"github.com/gin-gonic/gin"
)

// 创建登录类，用于得到登录信息
type UserInfo struct {
	UserName string `json:"username"`
	PassWord string `json:"password"`
}

func Login(c *gin.Context) {
	//得到返回对象
	returndata := config.NewReturnData()
	//获取登录信息
	userinfo := UserInfo{}
	err := c.ShouldBindJSON(&userinfo)
	if err != nil { //绑定失败
		logsutil.Info(map[string]interface{}{"message": "路由信息绑定失败"}, err.Error())
		returndata.Status = 401
		returndata.Message = err.Error()
	} else { //绑定成功
		logsutil.Debug(map[string]interface{}{
			"UserName": userinfo.UserName,
			"PassWord": userinfo.PassWord,
		}, "接下来开始验证登录信息")
		//连接数据库得到验证信息
		//为方便先自己设置
		testusername := "1"
		testpassword := "2"
		if testusername == userinfo.UserName && testpassword == userinfo.PassWord { //验证登录信息成功
			// 生成token
			ss, err := jwtutil.CreatToken(userinfo.UserName)
			if err != nil { //生成失败
				returndata.Status = 401
				returndata.Message = "稍后再试,当前生成token失败"
				c.JSON(returndata.Status, returndata)
			} else { //生成成功
				returndata.Data["token"] = ss
				returndata.Status = 200
				returndata.Message = "登录成功"
				c.JSON(returndata.Status, returndata)
			}
		} else { //验证登录信息不成功
			logsutil.Info(map[string]interface{}{"UserName": userinfo.UserName}, "登录失败,用户名或者密码错误")
			returndata.Status = 200
			returndata.Message = "登录失败,用户名或者密码错误"
			c.JSON(returndata.Status, returndata)
		}
	}
}
